from kivy.lang import Builder
from kivy.properties import NumericProperty, ObjectProperty, DictProperty
from kivy.uix.screenmanager import Screen

Builder.load_file('goblinoid/root/goblinscreen.kv')


class GoblinScreen(Screen):
    transition_priority = NumericProperty()
    dynamic_props = DictProperty({})

    def __init__(self, transition_priority, **kwargs):
        self.register_event_type('on_back_pressed')
        self.register_event_type('on_new_screen')
        self.register_event_type('on_return')
        self.register_event_type('on_comment')
        super(GoblinScreen, self).__init__(**kwargs)
        self.transition_priority = transition_priority

    def on_dynamic_props(self, instance, props):
        for prop in props:
            setattr(self, prop, props[prop])

    def get_dynamic_props(self):
        return dict([(prop, getattr(self, prop)) for prop in self.dynamic_props])

    def on_new_screen(self, **kwargs):
        return False

    def on_back_pressed(self, **kwargs):
        return False

    def on_return(self, **kwargs):
        return False

    def on_comment(self, **kwargs):
        return False


class GoblinScreenWithManager(GoblinScreen):
    screen_stack = ObjectProperty()
    screen_provider = ObjectProperty()
    sm_transition = ObjectProperty()

    def on_new_screen(self, **kwargs):
        response_handled = self.ids.sm.current_screen.dispatch(
            'on_new_screen',
            **kwargs)
        if not response_handled:
            self.ids.sm.open_screen(**kwargs)
        return True

    def on_back_pressed(self, **kwargs):
        response_handled = self.ids.sm.current_screen.dispatch(
            'on_back_pressed',
            **kwargs)
        if response_handled:
            return True
        else:
            if self.ids.sm.has_previous_screen():
                self.ids.sm.open_previous_screen()
                return True
            return False

    # TODO: combine on_return and on_comment
    def on_return(self, **kwargs):
        response = self.ids.sm.current_screen.dispatch(
            'on_return',
            **kwargs)
        if not response:
            self.ids.sm.refresh_current_screen()
        return True

    def on_comment(self, **kwargs):
        response = self.ids.sm.current_screen.dispatch(
            'on_comment',
            **kwargs)
        if not response:
            self.ids.sm.refresh_current_screen()
        return True


class GoblinScreenWithPrevious(GoblinScreen):

    def open_previous(self):
        if self.manager is not None:
            self.manager.open_previous_screen()
